package cn.iocoder.yudao.module.picturebook.service.audiorecord;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.picturebook.controller.admin.audio.vo.AudioRespVO;
import cn.iocoder.yudao.module.picturebook.controller.admin.audio.vo.AudioVO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.audio.AudioDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.audio.AudioMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.book.BookMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.yudao.module.picturebook.controller.admin.audiorecord.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.audiorecord.AudioRecordDO;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.audiorecord.AudioRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 绘本全音频 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AudioRecordServiceImpl implements AudioRecordService {

    @Resource
    private AudioRecordMapper audioRecordMapper;
    @Resource
    private AudioMapper audioMapper;
    @Resource
    private BookMapper bookMapper;

    @Override
    public Integer createAudioRecord(AudioRecordSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }

        // 插入
        AudioRecordDO audioRecord = BeanUtils.toBean(createReqVO, AudioRecordDO.class);
        audioRecordMapper.insert(audioRecord);

        // 添加空值检查
        if (audioRecord.getAudioId() == null) {
            throw new RuntimeException("Failed to create audio record, audioId is null");
        }

        // 返回
        return audioRecord.getAudioId();
    }

    @Override
    public void updateAudioRecord(AudioRecordSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null || updateReqVO.getAudioId() == null) {
            throw new IllegalArgumentException("请求参数或音频ID不能为空");
        }

        // 校验存在
        validateAudioRecordExists(updateReqVO.getAudioId());
        // 更新
        AudioRecordDO updateObj = BeanUtils.toBean(updateReqVO, AudioRecordDO.class);
        audioRecordMapper.updateById(updateObj);
    }


    @Override
    public void deleteAudioRecord(Integer id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("音频记录ID不能为空");
        }

        // 校验存在
        validateAudioRecordExists(id);
        // 删除
        audioRecordMapper.deleteByBookId(id);
    }

    @Override
    public void deleteAudioRecordListByIds(List<Integer> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("音频记录ID列表不能为空");
        }

        // 删除
        audioRecordMapper.deleteByIds(ids);
    }


    private void validateAudioRecordExists(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("音频记录ID不能为空");
        }

        if (audioRecordMapper.selectById(id) == null) {
            throw exception(AUDIO_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public AudioRecordDO getAudioRecord(Integer id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("音频记录ID不能为空");
        }

        return audioRecordMapper.selectById(id);
    }

    @Override
    public AudioVO getAudioRecordPage(AudioRecordPageReqVO pageReqVO, Long userId) {
        // 参数校验
        if (pageReqVO == null) {
            throw new IllegalArgumentException("分页请求参数不能为空");
        }
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        PageResult<AudioRecordDO> audioRecordDOPageResult = audioRecordMapper.selectPage(pageReqVO, userId);
        // 拼接数据
        AudioVO audioVO = new AudioVO();
        audioVO.setGatherName("最近");
        audioVO.setBookCount(Math.toIntExact(audioRecordDOPageResult.getTotal()));
        List<AudioRespVO> audioRespVOList = new ArrayList<>();
        //获取绘本的信息
        if (audioRecordDOPageResult.getList() != null) {
            for (AudioRecordDO audioRecordDO : audioRecordDOPageResult.getList()) {
                if (audioRecordDO != null) {
                    BookDO bookDO = bookMapper.selectById(audioRecordDO.getBookId());
                    AudioRespVO audioRespVO = new AudioRespVO();
                    if (bookDO != null) {
                        audioRespVO.setBookName(bookDO.getTitle());
                        audioRespVO.setBookId(audioRecordDO.getBookId());
                        audioRespVO.setBookCover(bookDO.getCoverUrl());
                    }
                    audioRespVO.setAudioIdUrl(audioRecordDO.getAudioIdUrl());
                    audioRespVOList.add(audioRespVO);
                }
            }
        }
        audioVO.setAudioList(audioRespVOList);
        return audioVO;

    }

    @Override
    public void createAudioRecordByUser(AudioRecordSaveReqVO createReqVO, Long userId) {
        // 参数校验
        if (createReqVO == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        // 先验证是否存在
        AudioRecordDO audioRecordDO = audioRecordMapper.selectByAudioId(createReqVO.getAudioId());
        AudioDO audioDO = audioMapper.selectById(createReqVO.getAudioId());
        if (audioRecordDO != null) {
            // 如果存在则更新时间及其他字段
            audioRecordDO.setUpdateTime(LocalDateTime.now());
            if (audioDO != null) {
                audioRecordDO.setBookId(audioDO.getBookId());
                audioRecordDO.setAudioIdUrl(audioDO.getAudioIdUrl());
            }
            audioRecordMapper.updateById(audioRecordDO);
        } else {
            if (audioDO == null) {
                // 可根据业务需求抛出异常或记录日志
                throw new IllegalArgumentException("AudioDO not found for audioId: " + createReqVO.getAudioId());
            }
            AudioRecordDO audioRecord = AudioRecordDO.builder()
                    .audioId(createReqVO.getAudioId())
                    .bookId(audioDO.getBookId())
                    .audioIdUrl(audioDO.getAudioIdUrl())// 保持字段一致性
                    .build();

            audioRecordMapper.insertByUserId(audioRecord.getAudioId(), audioRecord.getBookId(), audioRecord.getAudioIdUrl(), userId);
        }
    }


}